package springapp.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import springapp.service.PriceIncreaseValidator;
import springapp.service.ProductManager;
import springapp.service.PriceIncrease;

@Controller
@RequestMapping("/priceincrease.htm")
public class PriceIncreaseFormController {

    /*Logger for this class and subclasses*/
    protected final Log logger = LogFactory.getLog(getClass());

    private ProductManager productManager;

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(ModelMap model,@ModelAttribute("priceIncrease") PriceIncrease priceIncrease,
		BindingResult result) {
		
		PriceIncreaseValidator priceIncreaseValidator = new PriceIncreaseValidator ();
		priceIncreaseValidator.validate(priceIncrease, result);
		if (result.hasErrors() ){
			return "priceincrease";
		}else{
	        int increase = priceIncrease.getPercentage();
	        logger.info("Increasing prices by " + increase + "%.");

	        productManager.increasePrice(increase);

	        logger.info("returning from PriceIncreaseForm view to " + "Success");

	        return "success";
		}
    }

	@RequestMapping(method = RequestMethod.GET)
	public String initForm(ModelMap model){
        PriceIncrease priceIncrease = new PriceIncrease();
        priceIncrease.setPercentage(20);
		model.addAttribute("priceIncrease", priceIncrease);
		System.out.println("TEST:PriceIncreaseFormController.initForm Excute");
        return "priceincrease";
    }


    public void setProductManager(ProductManager productManager) {
        this.productManager = productManager;
    }

    public ProductManager getProductManager() {
        return productManager;
    }

}
